<template>
  <div class="container">
    <el-row :gutter="20" class="query-box">
      <el-col :span="24">
        <el-form :inline="true">
          <el-form-item label="日期类型:">
            <el-radio-group v-model="dateType">
              <el-radio-button label="1">年</el-radio-button>
              <el-radio-button label="2">月</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="日期范围:">
            <template v-if="dateType === '1'">
              <div class="year-range">
                <el-date-picker
                  v-model="startYear"
                  type="year"
                  placeholder="开始年份"
                  value-format="yyyy"
                  :clearable="false"
                  class="year-picker"
                  style="width: 120px"
                  popper-class="show-back-class date-select-class"
                />
                <span>至</span>
                <el-date-picker
                  v-model="endYear"
                  type="year"
                  :disabledDate="endYearDisabledDate"
                  placeholder="结束年份"
                  value-format="yyyy"
                  :clearable="false"
                  popper-class="show-back-class date-select-class"
                  class="year-picker"
                  style="width: 120px"
                />
              </div>
            </template>

            <el-date-picker
              v-else
              v-model="dateRange"
              popper-class="show-back-class date-select-class"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              value-format="yyyy-MM"
            />
          </el-form-item>


<!--          <el-form-item label="数据类型:">-->
<!--            <el-checkbox-group v-model="selectedTypes">-->
<!--              <el-checkbox-->
<!--                v-for="type in typeOptions"-->
<!--                :key="type.value"-->
<!--                :label="type.value"-->
<!--              >-->
<!--                {{ type.label }}-->
<!--              </el-checkbox>-->
<!--            </el-checkbox-group>-->
<!--          </el-form-item>-->

          <el-form-item label="化石燃料:">
            <el-checkbox-group v-model="selectedTypes">
              <el-checkbox
                v-for="type in type1Options"
                :key="type.value"
                :label="type.value"
              >
                {{ type.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="电力热力:">
            <el-checkbox-group v-model="selectedTypes">
              <el-checkbox
                v-for="type in type2Options"
                :key="type.value"
                :label="type.value"
              >
                {{ type.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="过程排放:">
            <el-checkbox-group v-model="selectedTypes">
              <el-checkbox
                v-for="type in type3Options"
                :key="type.value"
                :label="type.value"
              >
                {{ type.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>


          <el-form-item label="碳交易:">
            <el-checkbox-group v-model="selectedTypes">
              <el-checkbox
                v-for="type in type4Options"
                :key="type.value"
                :label="type.value"
              >
                {{ type.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>


          <el-form-item label="碳抵消:">
            <el-checkbox-group v-model="selectedTypes">
              <el-checkbox
                v-for="type in type5Options"
                :key="type.value"
                :label="type.value"
              >
                {{ type.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>



        </el-form>
      </el-col>
    </el-row>

    <!-- 内容区域 -->
    <el-row :gutter="20" class="content-area">
      <!-- 柱状图 -->
      <el-col :span="14">
        <div ref="chart" style="height: 400px;"></div>
      </el-col>

      <!-- 数据表格 -->
      <el-col :span="10">
        <el-table :data="tableData" border height="400">
          <el-table-column prop="iname" label="名称" align="center" />
          <el-table-column prop="creationTime" label="日期" align="center"/>
          <el-table-column prop="carbonEmissions" label="排放/减排量(t)" align="center"/>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {selectResult} from "@/api/dimensionsAnalysis/dimensionsAnalysis";

export default {
  data() {
    return {
      startYear: new Date().getFullYear().toString(),
      endYear: new Date().getFullYear().toString(),
      dateType: '1',
      dateRange: [],
      // typeOptions: [
      //   { label: '化石燃料', value: '1' },
      //   { label: '电力热力', value: '2' },
      //   { label: '过程排放', value: '3' },
      //   { label: '碳交易', value: '4' },
      //   { label: '碳抵消', value: '5' }
      // ],

      type1Options: [
        { label: '固体燃料', value: '1' },
        { label: '气体燃料', value: '2' },
        { label: '液体燃料', value: '3' },
      ],
      type2Options: [
        { label: '电力排放', value: '4' },
        { label: '热力排放', value: '5' },
      ],
      type3Options: [
        { label: '脱硫排放', value: '6' },
        { label: '脱硝排放', value: '7' },
        { label: '爆破过程排放', value: '8' },
        { label: '气体切割、焊接或加热过程释放', value: '9' },
        { label: '直接释放', value: '10' },
      ],
      type4Options: [
        { label: 'CCER', value: '11' },
        { label: '碳汇普', value: '12' },
      ],
      type5Options: [
        { label: '绿化', value: '13' },
        { label: '回收利用', value: '14' },
        { label: '绿证', value: '15' }
      ],

      // selectedTypes: ['1', '2', '3', '4', '5'],
      selectedTypes: ['1', '2', '3', '4', '5','6', '7', '8', '9', '10','11', '12', '13', '14', '15'],
      chartInstance: null,
      tableData: [],
      projectId: '',
      startDate: '',
      lastDate: '',
    }
  },
  watch: {
    dateType(newVal) {
      if (newVal === '1') {  // 修改为字符串判断
        const currentYear = new Date().getFullYear()
        this.startYear = `${currentYear - 1}`
        this.endYear = `${currentYear}`
      } else {
        // 使用原生Date处理月份初始化
        const currentDate = new Date()
        const year = currentDate.getFullYear()
        const month = (currentDate.getMonth() + 1).toString().padStart(2, '0')
        this.dateRange = [`${year}-${month}`, `${year}-${month}`]
      }
    }
  },
  created() {
    this.projectId = this.$store.state.projectDict.projectId;
    this.selectResultFun();
  },
  mounted() {
    this.initChart()
    // this.fetchData()
  },

  methods: {
    // 初始化图表
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chart)
      const option = {
        title: { text: '碳排放统计', left: 'center',textStyle: { color: '#ffffff' } },
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category',axisLabel: {  rotate: 45,  color: '#ffffff' } },
        yAxis: { type: 'value',axisLabel: {  color: '#ffffff' } },
        series: [{ type: 'bar' }]
      }
      this.chartInstance.setOption(option)
    },

    // 处理查询
    handleQuery() {
      if (this.dateType === '1') {
        const start = parseInt(this.startYear)
        const end = parseInt(this.endYear)
        if (start > end) {
          this.$message.error('开始年份不能晚于结束年份')
          return
        }
      }
      this.fetchData()
      this.selectResultFun();
    },

    // 结束年份不能早于开始年份
    endYearDisabledDate(time) {
      const startYear = parseInt(this.startYear)
      return new Date(time).getFullYear() < startYear
    },

    async fetchData() {
      // 生成正确的日期范围字符串
      const dateStr = this.dateType === '1'
        ? `${this.startYear} 至 ${this.endYear}`
        : this.dateRange.join(' 至 ')

      const mockData = this.selectedTypes.map(type => ({
        name: this.typeOptions.find(t => t.value === type).label,
        value: Math.floor(Math.random() * 1000) + 500,
        date: dateStr
      }))

      this.tableData = mockData
      this.updateChart(mockData)
    },

    // 更新图表数据
    updateChart(data) {
      const option = {
        xAxis: { axisLabel: { interval: 0 },data: data.map(item => item.name) },
        series: [{
          data: data.map(item => item.value),
          barWidth: 25,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }]
      }
      this.chartInstance.setOption(option)
    },
    selectResultFun() {
      selectResult({
        projectId: this.projectId,
        dateType: this.dateType,
        startDate: this.dateType == 1? this.startYear:this.dateRange[0],
        lastDate: this.dateType == 1? this.endYear:this.dateRange[1],
        dataType: this.selectedTypes
      }).then(res => {
        this.tableData = [];
        let chartData = [];
        this.tableData = res.data.finalList;
        // for(let i = 0; i < this.selectedTypes.length; i++) {
        //   if(this.selectedTypes[i] == '1') {
        //     chartData.push({name:"化石燃料",value:res.data.fossilFuelEmission})
        //   } else if(this.selectedTypes[i] == '2') {
        //     chartData.push({name:"电力热力",value:res.data.eleHeatEmission})
        //   } else if(this.selectedTypes[i] == '3') {
        //     chartData.push({name:"过程排放",value:res.data.processEmission})
        //   } else if(this.selectedTypes[i] == '4') {
        //     chartData.push({name:"碳交易",value:res.data.carbonTradeEmission})
        //   } else {
        //     chartData.push({name:"碳抵消",value:res.data.carbonOffsetEmission})
        //   }
        // }
        for(let i = 0; i < this.selectedTypes.length; i++) {
          if(this.selectedTypes[i] == '1') {
            chartData.push({name:"固体",value:res.data.solidFuelEmission})
          } else if(this.selectedTypes[i] == '2') {
            chartData.push({name:"气体",value:res.data.gasFuelEmission})
          } else if(this.selectedTypes[i] == '3') {
            chartData.push({name:"液体",value:res.data.liquidFuelEmission})
          } else if(this.selectedTypes[i] == '4') {
            chartData.push({name:"电力",value:res.data.powerEmission})
          }else if(this.selectedTypes[i] == '5') {
            chartData.push({name:"热力",value:res.data.heatEmission})
          }else if(this.selectedTypes[i] == '6') {
            chartData.push({name:"脱硫",value:res.data.sulfurEmission})
          }else if(this.selectedTypes[i] == '7') {
            chartData.push({name:"脱硝",value:res.data.nitreEmission})
          }else if(this.selectedTypes[i] == '8') {
            chartData.push({name:"爆破",value:res.data.blastEmission})
          }else if(this.selectedTypes[i] == '9') {
            chartData.push({name:"切焊加热",value:res.data.weldHeatEmission})
          }else if(this.selectedTypes[i] == '10') {
            chartData.push({name:"直接释放",value:res.data.directReleaseEmission})
          }else if(this.selectedTypes[i] == '11') {
            chartData.push({name:"CCER",value:res.data.ccerEmission})
          }else if(this.selectedTypes[i] == '12') {
            chartData.push({name:"碳汇普",value:res.data.carbonEmission})
          }else if(this.selectedTypes[i] == '13') {
            chartData.push({name:"绿化",value:res.data.greenCarbonSinkEmission})
          }else if(this.selectedTypes[i] == '14') {
            chartData.push({name:"回收利用",value:res.data.recyclingEmission})
          } else {
            chartData.push({name:"绿证",value:res.data.greenCertificateEmission})
          }
        }
        this.updateChart(chartData)
      })
    }
  }
}
</script>


<style scoped>
.container {
  padding-left: 20px;
}
.query-box {
  margin-bottom: 20px !important;
  padding-top: 10px;
  background: #07314E;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.content-area {
  margin-top: 0px; /* 增加顶部间距 */
}

.year-range {
  display: flex;
  align-items: center;
}

.year-picker {
  margin-right: 5px;
}

.year-range span {
  margin-right: 25px; /* 调整 "至" 的位置 */
}

::v-deep .el-form-item {
  margin-right: 40px !important;
  margin-bottom: 20px !important;
}

::v-deep {
.el-radio-group {
  margin-right: 30px;
}
.el-date-editor {
  margin-right: 30px;
}
.el-checkbox-group {
  margin-right: 20px;
}
.el-checkbox {
  margin-right: 25px;
}
}
</style>
<style lang="scss">
.date-select-class {
  background-color: rgba(17,93,131,255) !important;
}
.el-month-table td.start-date .cell, .el-month-table td.end-date .cell {
  background-color: #4ec3ff;
  color: #FFFFFF;
}
.el-month-table td.in-range div {
  background-color: #2496c9;
}
</style>
